package forminrecipe.GUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import forminrecipe.core.Core;
import forminrecipe.data.SQLSettings;
import forminrecipe.data.constants;

public class OptionPanel extends JPanel {
	private Core coreRef;
	private SQLSettings sqlSettings;
	
	private JLabel sqlAddressLabel;
	private JTextField sqlAddressTextField;
	
	private JLabel sqlUserNameLabel;
	private JTextField sqlUserNameTextField;
	
	private JLabel sqlPasswordLabel;
	private JTextField sqlPasswordTextField;
	
	private JLabel sqlDbNameLabel;
	private JTextField sqlDbNameTextField;
	
	private JButton saveChangesButton;
	private JButton cancelButton;
	
	
	public OptionPanel (SQLSettings sqlSet, Core core){
		coreRef = core;
		sqlSettings = sqlSet;
		
		sqlAddressLabel = new JLabel(constants.OPTION_PANEL_ADDRESS_LABEL);
		sqlAddressTextField = new JTextField(sqlSettings.sqlAddress);
		sqlAddressTextField.setEditable(true);
		this.add(sqlAddressLabel);
		this.add(sqlAddressTextField);
		
		sqlUserNameLabel = new JLabel(constants.OPTION_PANEL_USERNAME_LABEL);
		sqlUserNameTextField = new JTextField(sqlSettings.sqlUserName);
		sqlUserNameTextField.setEditable(true);
		this.add(sqlUserNameLabel);
		this.add(sqlUserNameTextField);
		
		sqlPasswordLabel = new JLabel(constants.OPTION_PANEL_PASSWORD_LABEL);
		sqlPasswordTextField = new JTextField(sqlSettings.sqlPassword);
		sqlPasswordTextField.setEditable(true);
		this.add(sqlPasswordLabel);
		this.add(sqlPasswordTextField);
		
		sqlDbNameLabel = new JLabel(constants.OPTION_PANEL_DBNAME_LABEL);
		sqlDbNameTextField = new JTextField(sqlSettings.sqlDbName);
		sqlDbNameTextField.setEditable(true);
		this.add(sqlDbNameLabel);
		this.add(sqlDbNameTextField);
		
		saveChangesButton = new JButton(constants.OPTION_PANEL_SAVE_BUTTON);
		saveChangesButton.addActionListener(new MyAction());
		cancelButton = new JButton(constants.OPTION_PANEL_CANCEL_BUTTON);
		cancelButton.addActionListener(new MyAction());
		this.add(saveChangesButton);
		this.add(cancelButton);
	}

	private void saveSettings(){
		sqlSettings.sqlAddress = sqlAddressTextField.getText();
		sqlSettings.sqlUserName = sqlUserNameTextField.getText();
		sqlSettings.sqlPassword = sqlPasswordTextField.getText();
		sqlSettings.sqlDbName = sqlDbNameTextField.getText();
		coreRef.saveSQLSettings(sqlSettings);
		
	}
	
	public class MyAction implements ActionListener{
	    public void actionPerformed(ActionEvent e){
	      String text = (String)e.getActionCommand();
	      
	      if(text == constants.OPTION_PANEL_SAVE_BUTTON){
	    	  saveSettings();
			
	      }else if(text==constants.OPTION_PANEL_CANCEL_BUTTON){

	      }
	    }
	}
}
